package com.nbcio.cd.integration;

import com.nbcio.cd.domain.CdFile;
import com.nbcio.cd.domain.CdFolder;
import com.nbcio.cd.mapper.CdFileMapper;
import com.nbcio.cd.mapper.CdFolderMapper;
import com.nbcio.cd.service.ICdFolderService;
import com.nbcio.cd.service.ICdUserStorageService;
import com.nbcio.cd.utils.CdPermissionUtils;
import com.nbcio.common.core.exception.ServiceException;
import com.nbcio.common.satoken.utils.LoginHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 项目管理与云网盘集成服务
 * 提供项目管理模块与云网盘的深度集成
 *
 * @author nbacheng
 * @date 2024-01-01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProjectCloudDriveIntegration {

    private final CdFolderMapper cdFolderMapper;
    private final CdFileMapper cdFileMapper;
    private final ICdFolderService cdFolderService;
    private final ICdUserStorageService cdUserStorageService;
    private final CdPermissionUtils permissionUtils;

    /**
     * 为项目创建文件夹
     *
     * @param projectId 项目ID
     * @param projectName 项目名称
     * @return 创建的文件夹ID
     */
    public Long createProjectFolder(Long projectId, String projectName) {
        try {
            // 检查项目文件夹是否已存在
            CdFolder existingFolder = cdFolderMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CdFolder>()
                    .eq(CdFolder::getProjectId, projectId)
                    .eq(CdFolder::getParentId, 0L)
                    .eq(CdFolder::getDelFlag, "0")
            );
            
            if (existingFolder != null) {
                log.info("项目文件夹已存在: projectId={}", projectId);
                return existingFolder.getFolderId();
            }
            
            // 创建项目文件夹
            CdFolder projectFolder = new CdFolder();
            projectFolder.setFolderName(projectName + " - 项目文档");
            projectFolder.setParentId(0L);
            projectFolder.setFolderPath("/project/" + projectId);
            projectFolder.setFolderType("project");
            projectFolder.setOwnerId(LoginHelper.getUserId());
            projectFolder.setProjectId(projectId);
            projectFolder.setFolderSize(0L);
            projectFolder.setFileCount(0);
            projectFolder.setFolderCount(0);
            projectFolder.setIsShared(true);
            projectFolder.setAccessLevel("restricted");
            projectFolder.setStatus("0");
            
            cdFolderMapper.insert(projectFolder);
            
            log.info("项目文件夹创建成功: projectId={}, folderId={}", projectId, projectFolder.getFolderId());
            return projectFolder.getFolderId();
            
        } catch (Exception e) {
            log.error("创建项目文件夹失败: projectId={}, error={}", projectId, e.getMessage(), e);
            throw new ServiceException("创建项目文件夹失败: " + e.getMessage());
        }
    }

    /**
     * 删除项目文件夹
     *
     * @param projectId 项目ID
     * @return 是否成功
     */
    public boolean deleteProjectFolder(Long projectId) {
        try {
            // 查找项目文件夹
            CdFolder projectFolder = cdFolderMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CdFolder>()
                    .eq(CdFolder::getProjectId, projectId)
                    .eq(CdFolder::getParentId, 0L)
                    .eq(CdFolder::getDelFlag, "0")
            );
            
            if (projectFolder == null) {
                log.info("项目文件夹不存在: projectId={}", projectId);
                return true;
            }
            
            // 递归删除文件夹及其内容
            cdFolderService.deleteByFolderId(projectFolder.getFolderId());
            
            log.info("项目文件夹删除成功: projectId={}, folderId={}", projectId, projectFolder.getFolderId());
            return true;
            
        } catch (Exception e) {
            log.error("删除项目文件夹失败: projectId={}, error={}", projectId, e.getMessage(), e);
            throw new ServiceException("删除项目文件夹失败: " + e.getMessage());
        }
    }

    /**
     * 获取项目的文件列表
     *
     * @param projectId 项目ID
     * @return 文件列表
     */
    public List<CdFile> getProjectFiles(Long projectId) {
        try {
            // 查找项目文件夹
            CdFolder projectFolder = cdFolderMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CdFolder>()
                    .eq(CdFolder::getProjectId, projectId)
                    .eq(CdFolder::getParentId, 0L)
                    .eq(CdFolder::getDelFlag, "0")
            );
            
            if (projectFolder == null) {
                return List.of();
            }
            
            // 递归获取所有文件
            return getFilesByFolderId(projectFolder.getFolderId());
            
        } catch (Exception e) {
            log.error("获取项目文件列表失败: projectId={}, error={}", projectId, e.getMessage(), e);
            throw new ServiceException("获取项目文件列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取项目文件夹信息
     *
     * @param projectId 项目ID
     * @return 文件夹信息
     */
    public CdFolder getProjectFolder(Long projectId) {
        return cdFolderMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CdFolder>()
                .eq(CdFolder::getProjectId, projectId)
                .eq(CdFolder::getParentId, 0L)
                .eq(CdFolder::getDelFlag, "0")
        );
    }

    /**
     * 检查用户是否有项目文件权限
     *
     * @param userId 用户ID
     * @param projectId 项目ID
     * @return 是否有权限
     */
    public boolean checkProjectFilePermission(Long userId, Long projectId) {
        CdFolder projectFolder = getProjectFolder(projectId);
        if (projectFolder == null) {
            return false;
        }
        
        // 检查用户对项目文件夹的权限
        return permissionUtils.checkFolderPermission(projectFolder.getFolderId(), CdPermissionUtils.PERMISSION_READ);
    }

    /**
     * 递归获取文件夹下的所有文件
     */
    private List<CdFile> getFilesByFolderId(Long folderId) {
        // 获取当前文件夹下的文件
        List<CdFile> files = cdFileMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CdFile>()
                .eq(CdFile::getFolderId, folderId)
                .eq(CdFile::getDelFlag, "0")
        );
        
        // 获取子文件夹
        List<CdFolder> subFolders = cdFolderMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CdFolder>()
                .eq(CdFolder::getParentId, folderId)
                .eq(CdFolder::getDelFlag, "0")
        );
        
        // 递归获取子文件夹下的文件
        for (CdFolder subFolder : subFolders) {
            files.addAll(getFilesByFolderId(subFolder.getFolderId()));
        }
        
        return files;
    }
}
